package com.fyzk.activity.news;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseFragment;
import com.fyzk.activity.app.AppToast;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtils;
import com.tyjc.lottery.R;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;

import java.util.List;

import com.wf.domain.UrlDef;

/**
 * <p>
 * @mood
 * @description
 * @author Administrator
 * @date 2018/7/18 11:17
 * </p>
 */
public class NewsTabFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OnItemClickListener{

    private static final String ARG_PARAM1 = "param1";
    private NewsTypeListBean.CategoryBean newsTypeInfo;

    private LinearLayoutManager mLayoutManager;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshLayout;

    private NewsAdapter mAdapter;
    private boolean isRefresh = true;//是否刷新中
    private boolean isLoading;//是否加载中

    private int currPage = 1;
    private int pageCount = 20;

    public static NewsTabFragment newInstance(NewsTypeListBean.CategoryBean newsTypeInfo) {
        NewsTabFragment fragment = new NewsTabFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, newsTypeInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            newsTypeInfo = (NewsTypeListBean.CategoryBean) getArguments().getSerializable(ARG_PARAM1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news_tab, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
        initListener();
    }

    private void initView(View view) {
        mRecyclerView = view.findViewById(R.id.newsTabUI_recyclerView);
        mRefreshLayout = view.findViewById(R.id.newsTabUI_refreshLayout);

        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRefreshLayout.setColorSchemeResources(R.color.top_bg);
        mAdapter = new NewsAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initData() {
        httpTabNewsData();
    }

    private void initListener() {
        mAdapter.setOnItemClickListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isSlidingToLast = false;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisibleItem = mLayoutManager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = mLayoutManager.getItemCount();
                    // isSlidingToLast 第一页显示的Item条数高度需要大于屏幕
                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                        //设置正在加载更多
                        mAdapter.changeMoreStatus(mAdapter.LOADING_MORE);
                        httpTabNewsData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0)
                    isSlidingToLast = true;
                else
                    isSlidingToLast = false;
            }
        });
    }

    /**
     * 获取新闻列表
     */
    protected void httpTabNewsData() {
        if(!isLoading) {
            isLoading = true;
            RequestParams params = new RequestParams(UrlDef.NEWS_URL + Commands.NEWSLIST);
            params.addBodyParameter("category", newsTypeInfo.getNickname());
            params.addBodyParameter("src", "src1");
            params.addBodyParameter("page", String.valueOf(currPage));
            params.addBodyParameter("perpage", String.valueOf(pageCount));
            params.addBodyParameter("iscontent", "0");
            sendRequestGet(HttpMethod.GET, 1, params);
        }
    }

    @Override
    protected void onSuccess(int requestCode, String result) {
        super.onSuccess(requestCode, result);
        LogUtils.e("====获取新闻列表result===="+result);
        isLoading = false;
        isRefresh = false;
        mRefreshLayout.setRefreshing(false);
        NewsListBean newsBeans = JSON.parseObject(result, NewsListBean.class);
        String status = newsBeans.getStatus();
        if ("200".equals(status)) {
            List<NewsListBean.DataBean> datas = newsBeans.getData();
            if (datas == null || datas.size() == 0) {
                if (currPage == 1) {
                    mAdapter.setHeadData(true);
                    mAdapter.getData().clear();
                    mAdapter.notifyDataSetChanged();
                } else {
                    //设置回到上拉加载更多
                    mAdapter.changeMoreStatus(mAdapter.NO_LOAD_MORE);
                    showToast("没有更多数据了");
                }
            } else {
                mAdapter.setHeadData(false);
                //设置回到上拉加载更多
                mAdapter.changeMoreStatus(mAdapter.NO_LOAD_MORE);
                if (currPage == 1) {
                    mAdapter.setData(datas);
                } else {
                    mAdapter.getData().addAll(datas);
                    mAdapter.notifyDataSetChanged();
                }
                currPage++;
            }
        }else{
            AppToast.getToast().show(newsBeans.getMsg());
        }
    }

    @Override
    protected void onFailure(int requestCode, String message) {
        super.onFailure(requestCode, message);
        isLoading = false;
        isRefresh = false;
        mRefreshLayout.setRefreshing(false);
        AppToast.getToast().show(message);
    }

    @Override
    public void onRefresh() {
        if(!isRefresh) {
            isRefresh = true;
            currPage = 1;
            httpTabNewsData();
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(getContext(), NewsDetailActivity.class);
        intent.putExtra("info", mAdapter.getData().get(position));
        startActivity(intent);
    }

}
